<?php
global $user;
global $base_url;
global $user;

// Lấy các thiết lập của module
$settings = variable_get ('paypal_settings', array ());

// Chuyển đổi giá trị tiền tệ tương ứng với tiện tệ đã chọn
if (function_exists ('dvcurrency_convert')) {
  dvcurrency_convert ($txn);
  
  // thay đổi currency code được chuyển đi
  $settings['currency_code'] = strtoupper ($txn->currency);
}

// Earmark the item_number since we never know if the admin is using Paypal
// for other services.
if ($txn->txnid) {
  $txnid = 'txnid_'. $txn->txnid;
}

$return_url = ($settings['return_url'] == '%order-history')
  ? url("store/history/$user->uid", NULL, NULL, TRUE)
  : url($settings['return_url'], NULL, NULL, TRUE);
  
$cancel_url = (strpos($settings['cancel_url'], 'http') !== 0)
  ? url($settings['cancel_url'], NULL, NULL, TRUE)
  : $settings['cancel_url'];

$item_name = $user->uid
  ? t("@site_name order #@txn_id for @user_name", array(
    '@site_name' => variable_get('site_name', 'Drupal'), 
    '@txn_id'=>$txn->txnid,
    '@user_name'=>$user->name
  ))
  : t("@site_name order #@txn_id", array(
    '@site_name' => variable_get('site_name', 'Drupal'), 
    '@txn_id' => $txn->txnid
  ));

$subtotal = store_transaction_calc_gross($txn);

$uri_array = array (
  'business'       => $settings['receiver_email'],
  'item_name'      => $item_name,
  'item_number'    => $txnid,
  'shipping'       => $txn->shipping_cost,
  'no_shipping'    => 1,
  'return'         => $return_url,
  'cancel_return'  => $cancel_url,
  'currency_code'  => $settings['currency_code'],
  'notify_url'     => url('paypal/ipn', NULL, NULL, TRUE),
  'paymentaction'  => paypal_connect_role_check ($user->uid) ? 'sale' : 'authorization'
);

if (($shipping = store_search_misc(array('type' => 'shipping'), $txn)) !== FALSE) {
  $uri_array['shipping'] = number_format($txn->misc[$shipping]->price, 2);
  $subtotal -= number_format($txn->misc[$shipping]->price, 2);
}

if (($tax = store_search_misc(array('type' => 'tax'), $txn)) !== FALSE) {
  $uri_array['tax'] = number_format($txn->misc[$tax]->price, 2);
  $subtotal -= number_format($txn->misc[$tax]->price, 2);
}

if (($handling = store_search_misc(array('type' => 'handling'), $txn)) !== FALSE) {
  $uri_array['handling'] = number_format($txn->misc[$handling]->price, 2);
  $subtotal -= number_format($txn->misc[$handling]->price, 2);
}

$uri_array['amount'] = number_format ($subtotal, 2);

foreach ($uri_array as $key => $value) {
  if (($key != 'business') && $value) {
    $value = urlencode($value);
  }

  if ($key == 'return' || $key == 'cancel_return') {
    $value = str_replace('%2F', '/', $value);
  }
  
  $uri .= "&$key=". $value;
}

$url = array($settings['url'], substr($uri, 1));

